package net.idugic.rpc.socket.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;

public class Serializer {

	private static ClassLoader loader = null;

	private static ClassLoader getClassLoader() {
		if (loader == null) {
			loader = Serializer.class.getClassLoader();
		}
		return loader;
	}

	public static byte[] serialize(Object object) {
		ByteArrayOutputStream byteOutputStream = null;
		ObjectOutputStream objectOutputStream = null;

		byte[] bytes = null;
		try {
			byteOutputStream = new ByteArrayOutputStream();
			objectOutputStream = new ObjectOutputStream(byteOutputStream);
			objectOutputStream.writeObject(object);
			bytes = byteOutputStream.toByteArray();
		} catch (Exception e) {
		} finally {
			try {
				objectOutputStream.flush();
				objectOutputStream.close();
				byteOutputStream.close();
			} catch (Exception e) {
			}
		}
		return bytes;
	}

	public static Object deserialize(byte[] input) {

		ObjectInputStream objectInputStream = null;
		Object myObject = null;
		try {
			objectInputStream = new ObjectInputStream(new ByteArrayInputStream(
					input)) {
				protected Class resolveClass(ObjectStreamClass objectStreamClass)
						throws IOException, ClassNotFoundException {
					return Class.forName(objectStreamClass.getName(), true,
							getClassLoader());
				}
			};
			myObject = (Object) objectInputStream.readObject();
		} catch (Exception e) {
		} finally {
			try {
				objectInputStream.close();
			} catch (Exception e) {
			}
		}
		return myObject;
	}

}